<template>
  <div>
      <div class="shopall" v-for="(item,index) in carList" :key="index">
         <span :class="['spanleft',item.flag? 'active':'']" @click="changspan(index)"></span>
      
      <home-item :item="item.shopdata">
           <template>
              <span @click.stop="changbtn(item,'del')">-</span>
              <span>{{item.count}}</span>
              <span @click.stop="changbtn(item,'add')">+</span>
           </template>
      </home-item>
      </div>
      <div class="shops">
           <span :class="['spanleft',flags? 'active':'']" @click="checkall">√</span> 
           <span>总价：{{sum}}</span> 
      </div>
  </div>
</template>

<script>
import {getCar,getUserInfo,addCar,removeCar} from "../../../api/api"
import homeItem from '@/components/homeItem'
export default {
  data(){
    return {
        carList:[],
        flags:false,
        sum:0,
    }
  },
  components:{
    homeItem
  },
  async created(){
    let user=await getUserInfo();
    let res=await getCar({
        user_id:user.data.data.uid
    });
    console.log(res);
    if(res.data.status == 200){
        res.data.data.forEach((item) => (item.flag=false));
        this.carList=res.data.data
    }

  },
  methods:{
      changspan(ind){         //反选
        this.carList[ind].flag=!this.carList[ind].flag;
        this.flags=this.carList.every((item)=>item.flag);
        this.getSum()
      },

      checkall(){         //全选
        this.flags=!this.flags;
        this.carList.forEach((item)=>(item.flag=this.flags));
        this.getSum()
      },
      async changbtn(item,type){
          let res =type == "add" ? await addCar({user_id:item.userid,shop_id:item.shopid}):await removeCar({ user_id:item.userid,shop_id:item.shopid})
          if(res.status == 200){
            type =="add" ? item.count++ :item.count--;
            this.getSum()
          }
      },
      getsum(){
        this.sum=this.carList.reduce((prve,next)=>{
            return prve + (next.flag? next.count * next.shopdata.price : 0)
        },0)
      }
  }
}
</script>

<style lang="scss">
.shopall,.shops{
     display: flex;
     .spanleft{
       height: 20px;
       width: 20px;
       border-radius: 100%;
       border: 1px solid #ccc;
       display: inline-block;
       color: #fff;
      &.active{
        background: red;
      }
     }
     .dls{
       flex: 1;
     }
}
.shops{
  height: 100px;
  padding-top: 20px;
}
</style>